package client.connect;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
public class HttpConnect {
    /**
     * 发送Get请求
     *
     * @param url    请求的接口
     * @param token  用于验证身份，登录时设为null即可
     * @param params 用于传递文本信息
     * @return 请求得到的文本
     */
    public String doGet(String url, String token, Map<String, String> params) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //拼接url
            if (params != null && params.size() > 0) {
                url += "?";
                StringBuilder urlBuilder = new StringBuilder(url);
                for (Map.Entry<String, String> param : params.entrySet()) {
                    urlBuilder.append(param.getKey()).append("=").append(param.getValue()).append("&");
                }
                urlBuilder.deleteCharAt(urlBuilder.length() - 1);
                url = urlBuilder.toString();
            }

            HttpGet httpGet = new HttpGet(url);
            //设置token
            httpGet.setHeader("Token", token);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(5000).build();//设置请求和传输超时时间
            httpGet.setConfig(requestConfig);

            //建立连接
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {
                //判断连接是否成功
                if (response.getStatusLine().getStatusCode() != 200) {
                    //输出错误信息
                    System.out.println("请求出错:at:" + url + "\n错误原因:" +
                            response.getStatusLine().getStatusCode() + response.getStatusLine().getReasonPhrase());
                    return null;
                }
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String ans = EntityUtils.toString(resEntity);
                    EntityUtils.consume(resEntity);
                    return ans;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 发送post请求
     *
     * @param url    请求接口
     * @param token  token,用于验证身份
     * @param params 用于传递文本信息,Map<String,String>形式
     * @param files  用于传递文件,Map<String, File>形式
     * @return 返回请求得到的文本
     */
    public String doPost(String url, String token, Map<String, String> params, Map<String, File> files) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);

            //装配请求参数
            MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                    .setCharset(StandardCharsets.UTF_8);
            if (files != null && files.size() > 0) {
                for (Map.Entry<String, File> file : files.entrySet()) {
                    builder.addPart(file.getKey(), new FileBody(file.getValue()));
                }
            }
            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> param : params.entrySet()) {
                    builder.addTextBody(param.getKey(), param.getValue(), ContentType.APPLICATION_JSON);
                }
            }

            //创建请求的entity
            HttpEntity reqEntity = builder.build();

            httpPost.setEntity(reqEntity);
            //设置token
            httpPost.setHeader("Token", token);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(5000).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                //判断连接是否成功
                if (response.getStatusLine().getStatusCode() != 200) {
                    //输出错误信息
                    System.out.println("请求出错:At:" + url + "\n错误原因:" +
                            response.getStatusLine().getStatusCode() + response.getStatusLine().getReasonPhrase());
                    return null;
                }
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String ans = EntityUtils.toString(resEntity);
                    EntityUtils.consume(resEntity);
                    return ans;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 发送post请求
     *
     * @param url    请求接口
     * @param token  token,用于验证身份
     * @param params 用于传递文本信息,Map<String,String>形式
     * @return 返回请求得到的文本
     */
    public String doPost(String url, String token, Map<String, String> params) {
        //初始化连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //声明post请求
        HttpPost post = new HttpPost(url);

        List<NameValuePair> pairs = new ArrayList<>();
        //建造一个装有数据的实体对象
        HttpEntity entity = null;
        try {
            //填充参数
            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> param : params.entrySet()) {
                    pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
            }
            entity = new UrlEncodedFormEntity(pairs, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //为post装配数据
        post.setEntity(entity);
        //设置token
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(5000).build();//设置请求和传输超时时间
        post.setConfig(requestConfig);
        post.addHeader("Token", token);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                System.out.println(statusCode + response.getStatusLine().getReasonPhrase());
                return "";
            }
            String result = "";
            try {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(response.getEntity());
            } catch (ParseException e) {
                e.printStackTrace();
                System.out.println("传回数据格式有误");
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    public InputStream getImageStream(String url) {
        try {

            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }

}
